package com.liu.webstore.interceptor;

import com.liu.webstore.entity.LoginTicket;
import com.liu.webstore.entity.User;
import com.liu.webstore.service.UserService;
import com.liu.webstore.util.CookieUtil;
import com.liu.webstore.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author LiuYumei
 * @Date 2022/7/23 10:09
 */
@Configuration
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // cookie从request传入的
        // 从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");
        if (null != ticket) {
            // 查询凭证，并且检查凭证是否有效及过期时间
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            if (null != loginTicket && loginTicket.getStatus() == 0
                    && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                User user = userService.getUserById(loginTicket.getUserId());
                // 在本次请求中暂存用户
                hostHolder.setUser(user);
                // 构建用户认证结果，并存入SecurityContext，以便于Security进行授权
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), userService.getAuthorities(user.getId()));
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (null != user && null != modelAndView) {
            modelAndView.addObject("loginUser", user);
        }
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 在整个请求结束后清除用户信息
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        // 清理认证
        SecurityContextHolder.clearContext();
    }
}
